package com.zhaozhaonews.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zhaozhaonews.article.service.ApArticleService;
import com.zhaozhaonews.article.service.ArticleFreemarkerService;
import com.zhaozhaonews.common.constants.ArticleConstants;
import com.zhaozhaonews.file.service.FileStorageService;
import com.zhaozhaonews.model.article.entity.ApArticle;
import com.zhaozhaonews.model.serach.vo.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author WanJl
 * @version 1.0
 * @title ArticleFreemarkerService
 * @description
 * @create 2025/2/20
 */
@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    //freemarker模板配置
    @Autowired
    private Configuration configuration;
    //上传图片服务
    @Autowired
    private FileStorageService fileStorageService;
    //新闻Service
    @Autowired
    private ApArticleService apArticleService;
    //kafka模板
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 生成静态文件上传到minIO中
     *
     * @param apArticle
     * @param content
     */
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        //0、获取新闻内容
        if(content == null){
            throw new RuntimeException("新闻内容为空");
        }
        //合成输出流
        StringWriter out = new StringWriter();
        try {
            //1、根据模板创建静态网页html文件
            Template template = configuration.getTemplate("article.ftl");
            //1.1 设置数据模型
            Map<String, Object> params = new HashMap<>();
            params.put("content", JSONArray.parseArray(content));
            template.process(params, out);
        }catch (Exception e){
            e.printStackTrace();
        }
        InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
        //2、把静态网页html文件上传到MinIO并生成这个静态网页文件的url访问路径
        String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", inputStream);
        //3、修改ap_article新闻表，把url路径保存到新闻表的static_url字段
        apArticleService.lambdaUpdate().eq(ApArticle::getId, apArticle.getId())
                .set(ApArticle::getStaticUrl, path)
                .update();
        //4、发送消息，创建搜索索引
        createArticleESIndex(apArticle,content,path);
    }

    /**
     * 发送消息，创建索引
     * @param apArticle
     * @param content
     * @param path
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String path) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, vo);
        vo.setContent(content);
        vo.setStaticUrl(path);

        //发送消息
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
        log.info("发送消息成功....");
    }
}
